<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1"/>
    <title>Dev Proxy</title>

    <!--  Download Resource https://highlightjs.org/download/ -->
    <link rel="stylesheet" href="css/monokai-sublime.min.css">
    <link rel="stylesheet" href="css/main.css">
    <script src="js/highlight.min.js"></script>
    <script src="js/main.js"></script>

    <style>
        body {
            /*background: #95a5a6;*/
            background: #aaaaaa;
        }
    </style>
</head>
<body>

<form style="text-align:center;">
    <!--顺序索引或者分页大小-->
    <input name="idx" style="width:60px;" type="number" id="idx" placeholder="idx" min="1" value="1"/>
    <input name="size" style="width:60px;" type="number" id="size" placeholder="size" min="1" value="12"/>

    <input name="id" style="width:120px;" id="id" placeholder="id"/>
    <button type="button" class="req-btn req-btn-replay" onclick="replay()">Run</button>
    <input type="date" id="date">
    <input name="kwd" id="kwd" style="width:280px;" placeholder="key word"/>
    <button type="button" class="req-btn req-btn-curl" onclick="search()">Search</button>
    <button type="button" class="req-btn req-btn-replay" onclick="refresh()">Reload</button>
    <button type="button" onclick="addPageNo(-1)" class="req-btn req-btn-curl">Pre</button>
    <button type="button" onclick="addPageNo(1)" class="req-btn req-btn-curl">Next</button>

    Page: <span id="pageDiv" onclick="setLastPage()" style="width: 40px"></span>
    Total: <span id="totalDiv" style="width: 40px"></span>

    <button type="button" onclick="OpenPage('ConfigPage')" class="req-btn req-btn-curl">Config</button>
    <button type="button" onclick="OpenPage('BenchPage')" class="req-btn req-btn-curl">Bench</button>
    <button type="button" onclick="OpenPage('PerfPage')" class="req-btn req-btn-curl">Perf</button>
    <!--    <a href="perf.html">性能分析</a>-->
    <a href="/debug/statsviz" target="_blank">Statsviz</a>
    <button type="button" onclick="exit()" class="req-btn req-btn-delete">Exit</button>

    <div id="ConfigPage" class="iframe-box">
        <div class="iframe-page">
            <iframe id="myFrame" src="config.html" class="iframe-self"></iframe>
        </div>
    </div>

    <div id="BenchPage" class="iframe-box">
        <div class="iframe-page">
            <iframe src="load.html" class="iframe-self"></iframe>
        </div>
    </div>
    <div id="PerfPage" class="iframe-box">
        <div class="iframe-page">
            <iframe src="/perf.html" class="iframe-self"></iframe>
        </div>
    </div>

</form>
<table id="req-log">
    <thead id="req-log-head">
    </thead>
    <tbody id="req-log-body" style="border: solid" class="req-log-body"></tbody>
</table>
<div id="detail">
    <div class="detail-nav">
        <span id="detail-nav-header" class="nav-inactive" onclick="showDetailTab('header')">Header</span>
        <span id="detail-nav-request" class="nav-inactive" onclick="showDetailTab('request')">Request</span>
        <span id="detail-nav-response" class="nav-inactive" onclick="showDetailTab('response')">Response</span>
    </div>
    <!--    <div id="active-detail-id"></div>-->
    <br>
    <div id="detail-request-head"></div>
    <div id="detail-request"></div>
    <div id="detail-response-head"></div>
    <div id="detail-response"></div>
</div>
<script>
    bindKeyDown()

    let lastDetailId
    let floatPages = ['ConfigPage', 'BenchPage', 'PerfPage']
    let reqDict = {}

    let tabGroup = [{
        key: 'header',
        header: document.getElementById("detail-nav-header"),
        win: [document.getElementById("detail-request-head"), document.getElementById("detail-response-head")]
    }, {
        key: 'request',
        header: document.getElementById("detail-nav-request"),
        win: [document.getElementById("detail-request")],
    }, {
        key: 'response',
        header: document.getElementById("detail-nav-response"),
        win: [document.getElementById("detail-response")],
    }]

    // 初始化
    init()

    function init() {
        search()
        let item = document.getElementById("kwd");
        item.addEventListener("keyup", function (event) {
            event.preventDefault();
            if (event.keyCode === 13) {
                search()
            }
        });

        document.getElementById("detail-request").innerHTML = ""
        document.getElementById("detail-response").innerHTML = ""
    }

    function bindKeyDown() {
        console.log("bind")
        document.onkeydown = function (event) {
            // Ctrl E
            if (event.ctrlKey === true && event.altKey === true) {
                console.log('hit')
                event.preventDefault();
                OpenPage('ConfigPage')
            }
        }
    }

    function OpenPage(id) {
        let obj = document.getElementById(id);
        if (!obj.style.display || obj.style.display === 'none') {
            obj.style.display = "block";
        } else {
            obj.style.display = "none";
        }

        for (let page of floatPages) {
            if (page === id) {
                continue
            }
            document.getElementById(page).style.display = "none";
        }
    }

    function refresh() {
        window.location.reload();
    }

    function addPageNo(delta) {
        let cur = document.getElementById("idx").value;
        let value = parseInt(cur) + delta;
        if (value < 1) {
            return;
        }
        document.getElementById("idx").value = value;
        refresh();
    }

    function showDetailTab(type) {
        for (let tab of tabGroup) {
            if (tab.key === type) {
                tab.header.setAttribute("class", "nav-active")
                for (let w of tab.win) {
                    w.style.display = "block"
                }
            } else {
                tab.header.setAttribute("class", "nav-inactive")
                for (let w of tab.win) {
                    w.style.display = "none"
                }
            }
        }
    }

    function showDetail(id, self) {
        if (id === lastDetailId) {
            return
        }
        lastDetailId = id
        let req = reqDict[id];
        // self.style.color = '#9b59b6'
        let start = new Date();
        console.log('render', start)
        let reH, resH, re, res;

        reH = JSON.stringify(req.request.header, null, 2);
        resH = JSON.stringify(req.response.header, null, 2);
        re = JSON.stringify(req.request.body, null, 2);
        res = JSON.stringify(req.response.body, null, 2);

        // document.getElementById("active-detail-id").innerText = id
        document.getElementById("detail-request-head").innerHTML = "<div class='req-req-head'> <pre class='hljs'><code>" + reH + "</code></pre></div>";
        document.getElementById("detail-response-head").innerHTML = "<div class='req-req-head'> <pre class='hljs'><code>" + resH + "</code></pre></div>"
        document.getElementById("detail-request").innerHTML = "<div class='req-req-body'> <pre class='hljs'><code>" + re + "</code></pre></div>"
        document.getElementById("detail-response").innerHTML = "<div class='req-rsp-body'> <pre class='hljs'><code>" + res + "</code></pre></div>"

        hljs.highlightAll()
        let end = new Date();
        console.log('finish', end, end - start, 'ms')
        // self.style.color = ''
    }

    function buildLine(i, l) {
        reqDict[l.id] = l

        return "<tr>" +
            "<td class='req-use-time' onclick='copyVal(\"" + l.id + "\")'> <span style='color:rebeccapurple'> [ " + (parseInt(i) + 1) + " ] </span> " + l.id + "</td>" +
            "<td style='font-size: small;width: 20px'> " + l.method + '<br/>' + l.statusCode + "</td>" +
            "<td> <div class='req-url'> " + l.url + " </div></td>" +
            "<td style='width: 90px;font-size: small;text-align: center' onclick='showDetail(\"" + l.id + "\", this)'>" + new Date(Date.parse(l.reqTime)).format('MM-dd hh:mm:ss') + "</td>" +
            "<td class='req-use-time' onclick='showDetail(\"" + l.id + "\", this)'>" + l.useTime + "</td>" +
            "<td style='padding: 0 2px 0 2px'> " +
            '<button type="button" class="req-btn req-btn-replay" onclick="replayById(\'' + l.id + '\')">Run</button>' +
            '<button type="button" class="req-btn req-btn-curl" onclick="copyCurlCommand(\'' + l.id + '\')">cUrl</button>' +
            '<button type="button" class="req-btn req-btn-page" onclick="perfPage(\'' + l.id + '\')">Perf</button>' +
            '<button type="button" class="req-btn req-btn-delete" onclick="deleteReq(\'' + l.id + '\')">Del</button>' +
            '</td>' +
            "</tr>";
    }

    function search() {
        reqDict = {};
        get("/list?" + appendParam("id", "idx", "date", "kwd", "size"), function (data) {
            let result = JSON.parse(data);
            let table = document.getElementById("req-log-body");
            table.innerHTML = ""
            if (!result.data) {
                return
            }

            document.getElementById("pageDiv").innerHTML = result.data.page
            document.getElementById("totalDiv").innerHTML = result.data.total
            if (!result.data.data || result.data.data.length <= 0) {
                return
            }

            for (let i in result.data.data) {
                let l = result.data.data[i]
                if (l == null) {
                    console.log('null value')
                    table.innerHTML += '<tr>null</tr>'
                } else {
                    table.innerHTML += buildLine(i, l)
                }
            }
        })
    }

    async function setLastPage() {
        document.getElementById("idx").value = document.getElementById("pageDiv").innerText
        search()
    }

    async function copyVal(txt) {
        await navigator.clipboard.writeText(txt)
    }

    function copyCurlCommand(id) {
        get("/curl?selfProxy=Y&id=" + id, async function (data) {
            await navigator.clipboard.writeText(data);
        })
    }

    function perfPage(id) {
        window.location = '/perf.html?id=' + id;
    }

    function deleteReq(id) {
        get("/del?id=" + id, function (data) {
            console.log(data)
            search()
        })
    }

    function replayById(id) {
        get("/replay?selfProxy=Y&id=" + id, function (data) {
            search()
            let maxLen = 400
            if (data && data.length > maxLen) {
                // console.log(data.substring(0,maxLen))
                alert(data.substring(0, maxLen) + "  ...")
            } else {
                alert(data);
            }
        })
    }

    function exit() {
        get('/exit')
    }

    function replay() {
        let id = val("id");
        if (!id || id === "") {
            alert("请输入重试请求的 id")
            return
        }
        replayById(id)
    }

</script>
</body>
</html>